package org.freemarker.web.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.Car;
import org.freemarker.core.model.Contact;
import org.freemarker.core.model.Gender;
import org.freemarker.core.service.CarService;
import org.freemarker.core.service.impl.ContactServiceImpl;
import org.freemarker.core.validator.Validator;
import org.freemarker.web.custom.CustomHttpServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


@Controller
public class ContactUpdateController extends CustomHttpServlet {
	private static final long serialVersionUID = -8793377116005779842L;
	private static final Logger logger = LoggerFactory
			.getLogger(ContactServiceImpl.class);
	
	@Autowired
	CarService carService;
	Validator validator = new Validator();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setAttribute("genders", Gender.values());
		
//		req.setAttribute("cars", carService.findNotUsed());
		req.getRequestDispatcher("views/contact/update.ftl").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String securityNumber = req.getParameter("securityNumber");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String telephone = req.getParameter("telephone");
		String email = req.getParameter("email");
		String birthdate = req.getParameter("birthdate");
		String genderValue = req.getParameter("gender");
		String nrMatricol = req.getParameter("car");
		
		
		Contact c = new Contact();
		c.setSecurityNumber(securityNumber);
		c.setFirstname(firstname);
		c.setLastname(lastname);
		c.setEmail(email);
		c.setTelephone(telephone);
		c.setGender(Gender.valueOf(genderValue));
		c.setBirthdate(createBirthDate(birthdate));
		
		Contact c2 = new Contact();
		try {
			c2 = contactService.getContactBySecurityNumber(c.getSecurityNumber());
		} catch (Exception e1) {
			String updtError;
			updtError="Contact not found in database!";
			List<Contact> users = contactService.findAll();
			req.setAttribute("users", users);
			req.setAttribute("updtError",updtError);
			req.getRequestDispatcher("views/contact/list.ftl").forward(req, resp);
		}
		
		List<String> errors = new ArrayList<String>();
		try {
			
			errors = validator.checkContactData(c);
			if (errors.size()>0){
				for(int i = 0; i < errors.size(); i++){
					System.out.println(errors.get(i));
					
				}
				List<Contact> users = contactService.findAll();
				req.setAttribute("users", users);
				req.setAttribute("errors",errors);
				req.getRequestDispatcher("views/contact/list.ftl").forward(req, resp);
				return;
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		Contact c3=contactService.getContactBySecurityNumber(c.getSecurityNumber());
		c3.setFirstname(firstname);
		c3.setLastname(lastname);
		c3.setEmail(email);
		c3.setTelephone(telephone);
		c3.setGender(Gender.valueOf(genderValue));
		c3.setBirthdate(createBirthDate(birthdate));
		contactService.update(c3);
		
		
		
		List<Contact> users = contactService.findAll();
		req.setAttribute("users", users);
		req.getRequestDispatcher("views/contact/list.ftl").forward(req, resp);
	
	}

	private Date createBirthDate(String bDateAsString) {
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		Date t = null;
		try {
			t = ft.parse(bDateAsString);
		} catch (ParseException e) {
			logger.debug("Exception when createing the birthdate " + e);
		}
		return t;
	}
}
